package com.ebt.m.share;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.WebView;
import android.widget.Toast;

import com.ebt.m.R;
import com.ebt.m.commons.utils.ClipBoardUtil;
import com.ebt.m.commons.utils.ToastUtil;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.ImageUtils;
import com.ebt.m.utils.fileutils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;


public class ShareUtils {
    private List<File> files = new ArrayList<>();

    public static String getZhFromEn(String platform, Context context) {
        if (TextUtils.isEmpty(platform)) {
            return "";
        }
        if ("QZone".equals(platform)) {
            return context.getString(R.string.share_QZone);
        }
        if ("Wechat".equals(platform)) {
            return context.getString(R.string.share_Wechat);
        }
        if ("WechatMoments".equals(platform)) {
            return context.getString(R.string.share_WechatMoments);
        }
        if ("QQ".equals(platform)) {
            return context.getString(R.string.share_QQ);
        }
        return platform;
    }

    /**
     * 此方法在微信7.0下调用会出现无法获取资源，无法分享
     *
     * @param mContext
     * @param flag         0/1
     * @param stringList
     * @param Kdescription
     * @param mType        微信好友    wchat flag=0
     *                     微信朋友圈 wchat flag =1
     *                     qq朋友圈  qq_zone flag = 1
     *                     qq好友 qq flag = 0
     */
    @Deprecated
    public void setShareImage(Activity mContext, final int flag, String[] stringList, final String Kdescription, final String mType) {

        if (mType.equals("qq") && !isAppAvilible(mContext, "com.tencent.mobileqq")) {
            Toast.makeText(mContext, "您还没有安装QQ", Toast.LENGTH_SHORT).show();
            return;
        } else if (mType.equals("wchat") && !isAppAvilible(mContext, "com.tencent.mm")) {
            Toast.makeText(mContext, "您还没有安装微信", Toast.LENGTH_SHORT).show();
            return;
        } else if (mType.equals("qq_zone") && !isAppAvilible(mContext, "com.qzone")) {
            Toast.makeText(mContext, "您还没有安装QQ空间", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < stringList.length; i++) {
                    File file = saveImageFromBase64(mContext, stringList[i]);
                    if (file != null) {
                        files.add(file);
                    }
                }
                Intent intent = new Intent();
                ComponentName comp;
                if (mType.contains("qq")) {
                    if (flag == 0) {
                        comp = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
                    } else {
                        comp = new ComponentName("com.qzone", "com.qzonex.module.operation.ui.QZonePublishMoodActivity");
                    }
                } else {
                    if (flag == 0) {
                        comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                    } else {
                        comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
//                        intent.putExtra("Kdescription", Kdescription);
                    }
                }

                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(Kdescription)) {
                            ClipBoardUtil.copy(mContext, Kdescription);
                            ToastUtil.show(mContext, "文本内容已经复制到剪贴板");
                        }
                    }
                });
                intent.setComponent(comp);
                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                intent.setType("image/*");
                ArrayList<Uri> imageUris = new ArrayList<Uri>();
                for (File f : files) {
                    imageUris.add(Uri.fromFile(f));
                }
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                if (imageUris.size() > 0) {
                    mContext.startActivity(intent);
                }
            }
        }).start();
    }

    EBTProgressDialog progressDialog = null;

    /**
     * 微信6.7.3之后不再支持多图分享到朋友圈
     *
     * @param mContext
     * @param flag
     * @param stringList
     * @param Kdescription
     * @param mType
     */
    public void shareImgs(Activity mContext, final int flag, String[] stringList, final String Kdescription, final String mType) {
//        if (stringList != null && stringList.length > 1) {
//            ToastUtil.show(mContext, "不支持多图分享");
//        }
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(Kdescription)) {
                    ClipBoardUtil.copy(mContext, Kdescription);
                    ToastUtil.show(mContext, "文本内容已经复制到剪贴板");
                }
            }
        });
        Observable.fromArray(stringList).map(new Function<String, Uri>() {
            @Override
            public Uri apply(String s) throws Exception {
                File file = saveImageFromBase64(mContext, s);
                Uri uri = ShareFileUtil.getFileUri(mContext, ShareContentType.IMAGE, file);
                return uri;
            }
        }).toList().doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                if (progressDialog == null) {
                    progressDialog = new EBTProgressDialog(mContext);
                    progressDialog.show();
                }
            }
        }).doAfterTerminate(new Action() {
            @Override
            public void run() throws Exception {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
            }
        }).subscribe(new Consumer<List<Uri>>() {
            @Override
            public void accept(List<Uri> uris) throws Exception {
                if (uris == null) {
                    return;
                }
                if (uris.size() == 1) {
                    new Share2.Builder(mContext)
                            .setContentType(ShareContentType.IMAGE)
                            .setShareFileUri(uris.get(0))
                            .setTitle("分享")
                            .build()
                            .shareBySystem();
                } else {
                    ArrayList arrayList = new ArrayList();
                    for (int i = 0; i < uris.size(); i++) {
                        arrayList.add(uris.get(i));
                    }
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                    shareIntent.addCategory("android.intent.category.DEFAULT");
                    shareIntent.setType(ShareContentType.IMAGE);
                    shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayList);
                    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    mContext.startActivity(shareIntent);
                }

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                throwable.printStackTrace();
            }
        });
    }

    /**
     * 分享后回调，由于使用系统的分享无法获取分享回调-故此处不精确
     *
     * @param webView
     * @param callback
     * @param callbackParams
     */
    public void afterShare(WebView webView, String callback, String callbackParams) {
        try {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:" + callback + "(" + callbackParams + ")");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据网络图片url路径保存到本地
     */
    public static final File saveImageToSdCard(Context context, String image) {
        boolean success = false;
        File file = null;
        try {
            file = createStableImageFile(context);
            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            FileOutputStream outStream;
            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (success) {
            return file;
        } else {
            return null;
        }
    }

    /**
     * 保存base64到文件
     *
     * @param context
     * @param base64Str
     * @return
     */
    public static File saveImageFromBase64(Context context, String base64Str) {
        File file = null;
        try {
            file = createStableImageFile(context);
            ImageUtils.base64ToFile(base64Str, file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        File imgCachePath = new File(ConfigData.CACHE_PATH + File.separator + "shareImgsCache");
        //先清空文件夹
        FileUtils.deleteFile(imgCachePath);
        if (!imgCachePath.exists()) {
            imgCachePath.mkdirs();
        }
        long i = System.currentTimeMillis();
        String imageFileName = i + ".png";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    //判断是否安装了微信,QQ,QQ空间
    public static boolean isAppAvilible(Context context, String mType) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(mType)) {
                    return true;
                }
            }
        }
        return false;
    }
}
